﻿using GuardMonitor.Model;
using GuardMonitor.Utils;
using Newtonsoft.Json.Linq;
using SmartWeighMonitor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using 新门禁.Utils;
using 门禁系统.ViewModel;

namespace 新门禁
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private MainViewModel mainViewModel;
        private MainWindow mainWindow;
        private DispatcherTimer timer;
        private HttpServer server;
        private System.Windows.Forms.PictureBox m_pictureBox01;
        private System.Windows.Forms.PictureBox m_pictureBox02;
        private int m_nPlayHandle01 = 0;
        private int m_nPlayHandle02 = 0;
        private SynchronizationContext _syncContext = null;
        private int handleIN;
        private int handleOUT;

        private delegate void MyDelegate(Object value);

        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB = null;
        private VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK m_PlateResultCB2 = null;
        private VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK m_gpio_recvCB = null;

        private string m_sAppPath;

        public MainWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;
            m_sAppPath = System.IO.Directory.GetCurrentDirectory();
            mainViewModel = new MainViewModel();
            this.DataContext = mainViewModel;

            m_pictureBox01 = new System.Windows.Forms.PictureBox();
            m_pictureBox02 = new System.Windows.Forms.PictureBox();
            videoHost01.Child = m_pictureBox01;
            videoHost02.Child = m_pictureBox02;

            mainWindow = this;
            this.Loaded += Window_Loaded;
            int seconds = App.GetBaseInfo().RefreshSeconds;
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(seconds);
            timer.Tick += new EventHandler(timeCycle);
            timer.Start();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            version.Text = "门禁系统 ver.1.0.1";
            VzClientSDK.VzLPRClient_Setup();
            m_gpio_recvCB = new VzClientSDK.VZLPRC_GPIO_RECV_CALLBACK(OnGPIORecv);

            server = App.GetHttpServer();
            if (null != server)
            {
                HttpServer.sendMsgEvent += Server_sendMsgEvent;
            }
            //LoadData();
            if (!"".Equals(App.GetBaseInfo().Camera_In_VideoUrl))//入口摄像头
            {
                String[] videoInfoArray = App.GetBaseInfo().Camera_In_VideoUrl.Split(',');

                payVideo(1, m_pictureBox01, videoInfoArray);
            }
            if (!"".Equals(App.GetBaseInfo().Camera_Out_VideoUrl))
            {
                String[] videoInfoArray = App.GetBaseInfo().Camera_Out_VideoUrl.Split(',');

                payVideo(2, m_pictureBox02, videoInfoArray);
            }

            LoadData();
            //if (null != server)
            //{
            //    HttpServer.sendVideoEvent += Server_sendScreenEvent;
            //}
        }

        private void OnGPIORecv(int handle, int nGPIOId, int nVal, IntPtr pUserData)
        {
            int value = nVal;
        }

        //private void Server_sendScreenEvent(object msg)
        //{
        //    MyDelegate dele2 = new MyDelegate(DealVideoMessage);
        //    this.Dispatcher.Invoke(dele2, msg);
        //}

        private void DealVideoMessage(object obj)
        {
            m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
        }

        private int OnPlateResult(int handle, IntPtr pUserData,
                                                 IntPtr pResult, uint uNumPlates,
                                                 VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType,
                                                 IntPtr pImgFull,
                                                 IntPtr pImgPlateClip)
        {
            if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
            {
                string save = App.GetBaseInfo().savePhoto;
                string PhotoPath = App.GetBaseInfo().PhotoPath;
                if (save.Equals("1"))
                {
                    VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
                    string strLicense = new string(result.license);

                    VzClientSDK.VZ_LPR_MSG_PLATE_INFO plateInfo = new VzClientSDK.VZ_LPR_MSG_PLATE_INFO();
                    plateInfo.plate = strLicense;

                    DateTime now = DateTime.Now;
                    string sTime = string.Format("{0:yyyyMMddHHmmssffff}", now);

                    string strFilePath = PhotoPath + "\\in\\";
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }
                    string carNumber = strLicense.Substring(0, 7);
                    string path = strFilePath + sTime + carNumber + ".jpg";

                    VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, path, 100);
                    plateInfo.img_path = path;

                    int size = Marshal.SizeOf(plateInfo);
                    IntPtr intptr = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(plateInfo, intptr, true);
                }

                //Win32API.PostMessage(hwndMain, MSG_PLATE_INFO, (int)intptr, handle);
            }

            return 0;
        }

        private int OnPlateResult2(int handle, IntPtr pUserData,
                                                  IntPtr pResult, uint uNumPlates,
                                                  VzClientSDK.VZ_LPRC_RESULT_TYPE eResultType,
                                                  IntPtr pImgFull,
                                                  IntPtr pImgPlateClip)
        {
            if (eResultType != VzClientSDK.VZ_LPRC_RESULT_TYPE.VZ_LPRC_RESULT_REALTIME)
            {
                string save = App.GetBaseInfo().savePhoto;
                string PhotoPath = App.GetBaseInfo().PhotoPath;
                if (save.Equals("1"))
                {
                    VzClientSDK.TH_PlateResult result = (VzClientSDK.TH_PlateResult)Marshal.PtrToStructure(pResult, typeof(VzClientSDK.TH_PlateResult));
                    string strLicense = new string(result.license);

                    VzClientSDK.VZ_LPR_MSG_PLATE_INFO plateInfo = new VzClientSDK.VZ_LPR_MSG_PLATE_INFO();
                    plateInfo.plate = strLicense;

                    DateTime now = DateTime.Now;
                    string sTime = string.Format("{0:yyyyMMddHHmmssffff}", now);

                    string strFilePath = PhotoPath + "\\out\\";
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }
                    string carNumber = strLicense.Substring(0, 7);

                    string path = strFilePath + sTime + carNumber + ".jpg";

                    VzClientSDK.VzLPRClient_ImageSaveToJpeg(pImgFull, path, 100);
                    plateInfo.img_path = path;

                    int size = Marshal.SizeOf(plateInfo);
                    IntPtr intptr = Marshal.AllocHGlobal(size);
                    Marshal.StructureToPtr(plateInfo, intptr, true);

                    //Win32API.PostMessage(hwndMain, MSG_PLATE_INFO, (int)intptr, handle);
                }
            }

            return 0;
        }

        private void payVideo(int idx, System.Windows.Forms.PictureBox picBox, String[] info)//摄像头
        {
            string ip = info[0];
            short nPort = Int16.Parse(info[1]);
            string username = info[2];
            string pass = info[3];

            int handle = 0;
            handle = VzClientSDK.VzLPRClient_Open(ip, (ushort)nPort, username, pass);//打开设备
            if (handle == 0)
            {
                return;
            }
            VzClientSDK.VzLPRClient_SetIsShowPlateRect(handle, 0);
            picBox.Image = null;
            if (idx == 1)
            {
                server.handleIN = handle;
                if (m_nPlayHandle01 > 0)
                {
                    VzClientSDK.VzLPRClient_StopRealPlay(m_nPlayHandle01);
                    m_nPlayHandle01 = 0;
                }
            }
            else if (idx == 2)
            {
                server.handleOUT = handle;
                if (m_nPlayHandle02 > 0)
                {
                    VzClientSDK.VzLPRClient_StopRealPlay(m_nPlayHandle02);
                    m_nPlayHandle02 = 0;
                }
            }
            VzClientSDK.VzLPRClient_SetVideoVBR(handle, 5);
            int lprHandle1 = 0;
            if (picBox.Tag != null)
            {
                string sHandle = picBox.Tag.ToString();
                lprHandle1 = Int32.Parse(sHandle);
            }
            if (lprHandle1 > 0)
            {
                VzClientSDK.VzLPRClient_SetPlateInfoCallBack(lprHandle1, null, IntPtr.Zero, 0);
            }
            if (idx == 1)
            {
                m_nPlayHandle01 = VzClientSDK.VzLPRClient_StartRealPlay(handle, picBox.Handle);//播放视频
                picBox.Tag = handle;
                m_PlateResultCB = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult);
                VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, m_PlateResultCB, IntPtr.Zero, 1);
                VzClientSDK.VzLPRClient_SetGPIORecvCallBack(handle, m_gpio_recvCB, IntPtr.Zero);//设置GPIO输入回调函数
            }
            else if (idx == 2)
            {
                m_nPlayHandle02 = VzClientSDK.VzLPRClient_StartRealPlay(handle, picBox.Handle);
                picBox.Tag = handle;
                m_PlateResultCB2 = new VzClientSDK.VZLPRC_PLATE_INFO_CALLBACK(OnPlateResult2);
                VzClientSDK.VzLPRClient_SetPlateInfoCallBack(handle, m_PlateResultCB2, IntPtr.Zero, 1);
            }
        }

        private void LoadData()
        {
            //new Task(() =>
            //{
            //    Invoke();
            //}).Start();

            new Task(() =>
            {
                getAccessList();
            }).Start();
        }

        private async void Invoke()
        {
            try
            {
                String gateCode = App.GetBaseInfo().gateCode;
                String[] gatecodes = gateCode.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                String ip = App.GetBaseInfo().HttpServerIp;
                String port = App.GetBaseInfo().HttpServerPort;
                //String port = App.GetBaseInfo().AuthHttpServerPort;
                JArray jArray = new JArray();
                for (int i = 0; i < gatecodes.Length; i++)
                {
                    JObject json = new JObject();
                    //json.Add("gateCode",gatecodes[i]);
                    json.Add("id", gatecodes[i]);
                    jArray.Add(json);
                }
                //String bodyJsonStr = "{\"gateCode\":\"" + gateCode + "\"}";
                JObject newJson = new JObject();
                newJson.Add("jsonList", jArray);
                var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/qd-s-factory/accessLists", newJson.ToString());
                ///qd-s-factory/access/accessList
                // var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port +
                // "/qd-s-factory/access/accessList", newJson.ToString());
                string str = await result;  //等待返回

                MyDelegate d = new MyDelegate(dealLoadData);
                this.Dispatcher.Invoke(d, str);
            }
            catch (Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Message");
            }
        }

        private async void getAccessList()
        {
            try
            {
                String gateCode = App.GetBaseInfo().gateCode;
                String[] gatecodes = gateCode.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                String ip = App.GetBaseInfo().HttpServerIp;
                String port = App.GetBaseInfo().HttpServerPort;
                //String port = App.GetBaseInfo().AuthHttpServerPort;
                JArray jArray = new JArray();
                for (int i = 0; i < gatecodes.Length; i++)
                {
                    JObject json = new JObject();
                    //json.Add("gateCode", gatecodes[i]);
                    json.Add("id", gatecodes[i]);
                    jArray.Add(json);
                }
                //String bodyJsonStr = "{\"gateCode\":\"" + gateCode + "\"}";
                JObject newJson = new JObject();
                newJson.Add("jsonList", jArray);
                var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/qd-s-factory/accessLists", newJson.ToString());
                //var result = HttpPostHelper.doHttpAsyncPost("http://" + ip + ":" + port + "/qd-s-factory/access/accessList", newJson.ToString());
                String msg = await result;
                JObject respJson = JObject.Parse(msg);
                String status = respJson["success"].ToString();
                if ("true".Equals(status.ToLower()))
                {
                    _syncContext.Post(SetDataLists, respJson);
                }
            }
            catch (Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Message");
            }
        }

        private void SetDataLists(object obj)
        {
            string flag = App.GetBaseInfo().ButtonLimit;
            try
            {
                JObject jsonObj = obj as JObject;
                bool success = (bool)jsonObj.GetValue("success");
                if (!success) return;
                int idx = 0;
                mainViewModel.carInList.Clear();
                JObject dataObj = (JObject)jsonObj.GetValue("data");
                JArray waitInArray = (JArray)dataObj.GetValue("willInList");
                String check = (String)jsonObj.GetValue("check");

                idx = 0;
                foreach (JObject item in waitInArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    if (flag.Equals("1"))
                    {
                        record.Visibility = "Visible";
                    }
                    else
                    {
                        record.Visibility = "Hidden";
                    }

                    if (flag.Equals("1"))
                    {
                        record.checkVisibility = "Visible";
                    }
                    else
                    {
                        record.checkVisibility = "Hidden";
                    }
                    mainViewModel.carInList.Add(record);
                }

                mainViewModel.carInList2.Clear();
                idx = 0;
                JArray hasInArray = (JArray)dataObj.GetValue("inList");
                foreach (JObject item in hasInArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    mainViewModel.carInList2.Add(record);
                }

                mainViewModel.carOutList.Clear();
                idx = 0;
                JArray waitOutArray = (JArray)dataObj.GetValue("willOutList");
                foreach (JObject item in waitOutArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    if (flag.Equals("1"))
                    {
                        record.Visibility = "Visible";
                    }
                    else
                    {
                        record.Visibility = "Hidden";
                    }
                    mainViewModel.carOutList.Add(record);
                }

                mainViewModel.carOutList2.Clear();
                idx = 0;
                JArray hasOutArray = (JArray)dataObj.GetValue("outList");
                foreach (JObject item in hasOutArray)
                {
                    idx++;
                    Record record = getRecordByJSON(item);
                    record.xh = idx.ToString();
                    mainViewModel.carOutList2.Add(record);
                }
            }
            catch (Exception ex)
            {
                LogObject.WriteLog("send message: ", "loadData");
            }
        }

        public Record getRecordByJSON(JObject item)
        {
            Record record = new Record();
            record.id = (String)item.GetValue("id");
            record.xh = (String)item.GetValue("xh");
            record.carNo = (String)item.GetValue("carNo");
            record.invName = (String)item.GetValue("invName");
            record.orderNo = (String)item.GetValue("orderNo");
            record.cTime = (String)item.GetValue("cTime");

            String status = (String)item.GetValue("checkStatus");
            if (status.Equals("0"))
            {
                record.CheckStatus = "待安检";
            }
            else if (status.Equals("1"))
            {
                record.CheckStatus = "安检通过";
            }
            else
            {
                record.CheckStatus = "安检未通过";
            }

            return record;
        }

        private void dealLoadData(Object obj)
        {
            // JToken didoControl = App.GetGlobalVariablesModel().DIDOControl;
            // LogObject.WriteLog("send message: " + didoControl, "didoControl");

            // JToken[] jTokens = didoControl.ToArray(); int tips1 = 0; int tips2 = 0; for (int i =
            // 0; i < jTokens.Length; i++) { //menuButton = jTokens[i].ToString(); if
            // (jTokens[i].ToString().Equals("WPF_DIDO")) { tips1 = 1;

            // } else if (jTokens[i].ToString().Equals("WPF_CHECK")) { tips2 = 1;

            // }

            //    }
            //JObject msgObj = (JObject)obj;
            //String check = (String)msgObj.GetValue("check");
            string buttonLimit = App.GetBaseInfo().ButtonLimit;

            mainViewModel.LoadData((string)obj, buttonLimit);
        }

        private void DGInList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        private void Server_sendMsgEvent(object msg)
        {
            MyDelegate dele = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(dele, msg);
        }

        private void DealMessage(object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");
            if ("GetCarNo".Equals(type))
            {
                JObject jsonDetail = (JObject)jsonObj.GetValue("detail");
                String inOut = (String)jsonDetail.GetValue("inOut");
                String carNo = (String)jsonDetail.GetValue("carNo");
                if ("in".Equals(inOut))
                {
                    txtInCarNo.Text = carNo;
                    txtInResult.Text = "";
                }
                else if ("out".Equals(inOut))
                {
                    txtOutCarNo.Text = carNo;
                    txtOutResult.Text = "";
                }
            }
            else if ("Check".Equals(type))
            {
                bool result = (bool)jsonObj.GetValue("result");
                String inOut = (String)jsonObj.GetValue("inOut");
                String message = (String)jsonObj.GetValue("message");

                if (result)
                {
                    if ("in".Equals(inOut))
                    {
                        txtInResult.Foreground = Brushes.Green;
                        txtInResult.Text = "正常放行";
                    }
                    else if ("out".Equals(inOut))
                    {
                        txtOutResult.Foreground = Brushes.Green;
                        txtOutResult.Text = "正常放行";
                    }
                    LoadData();
                }
                else
                {
                    if ("in".Equals(inOut))
                    {
                        txtInResult.Foreground = Brushes.Red;
                        txtInResult.Text = message;
                        //MessageBox.Show(message);
                    }
                    else if ("out".Equals(inOut))
                    {
                        txtOutResult.Foreground = Brushes.Red;
                        txtOutResult.Text = message;
                        //MessageBox.Show(message);
                    }
                }
            }
        }

        private void timeCycle(object sender, EventArgs e)
        {
            LoadData();
        }

        public void doDataRefresh(object sender, RoutedEventArgs e)
        {
            LoadData();
        }

        private void showPassWindowIn(object sender, RoutedEventArgs e)
        {
            //int idx = DGInList.SelectedIndex;
            //if (idx != 0)
            //{
            //    MessageBox.Show("只能按排队顺序放行");
            //    return;
            //}
            Record record = (Record)DGInList.SelectedItem;

            PassWindow passWindow = new PassWindow();
            passWindow.setInOutType("in");
            passWindow.setCarNo(record.carNo);
            passWindow.Owner = mainWindow;

            bool result = (bool)passWindow.ShowDialog();
            if (result)
            {
                txtInCarNo.Text = record.carNo;
                txtInResult.Foreground = Brushes.Green;
                txtInResult.Text = "手动放行";
                LoadData();
            }
        }

        private void showPassWindowOut(object sender, RoutedEventArgs e)
        {
            //int idx = DGOutList.SelectedIndex;
            //if (idx != 0)
            //{
            //    MessageBox.Show("只能按排队顺序放行");
            //    return;
            //}

            Record record = (Record)DGOutList.SelectedItem;

            PassWindow passWindow = new PassWindow();
            passWindow.setInOutType("out");
            passWindow.setCarNo(record.carNo);
            passWindow.Owner = mainWindow;

            bool result = (bool)passWindow.ShowDialog();
            if (result)
            {
                txtOutCarNo.Text = record.carNo;
                txtOutResult.Foreground = Brushes.Green;
                txtOutResult.Text = "手动放行";
                LoadData();
            }
        }

        private void showCheckWindowIn(object sender, RoutedEventArgs e)
        {
            Record record = (Record)DGInList.SelectedItem;
            CheckWindow checkWindow = new CheckWindow();
            checkWindow.setBillNo(record.id);
            checkWindow.Owner = mainWindow;
            bool result = (bool)checkWindow.ShowDialog();
            if (result)
            {
                LoadData();
            }
        }

        public void LED_PlayVoice(string VoiceText, byte Opt)
        {
            byte[] Buff = new byte[512];//分配缓冲数组
            byte[] TextBuff = System.Text.Encoding.Default.GetBytes(VoiceText); //把string 类型字符串 读取到字节数组里面.注意字符串编码必须是GB2312 WINDOWS代码页为936
            int Pos = 0;
            int TextLen = TextBuff.Length; //获取字符串数组的长度
            ushort CRC;

            if ((1 + TextLen) >= 255)
            { //数据最大不能超过255长度
                return;
            }

            /*0.填充显示命令参数*/
            Buff[Pos++] = 0x00; //显示屏地址
            Buff[Pos++] = 0x64; //固定参数
            Buff[Pos++] = 0xFF; //包序列
            Buff[Pos++] = 0xFF; //包序列
            Buff[Pos++] = 0x30; //指令
            Buff[Pos++] = (byte)(1 + TextLen); //数据长度
            Buff[Pos++] = Opt; //播放选项
            /*1.复制语音文本内容到缓冲区*/
            for (int i = 0; i < TextLen; i++)
            {
                Buff[Pos++] = TextBuff[i];
            }
            /*2.计算校验码*/
            CRC = MB_CRC16(ref Buff, Pos);
            Buff[Pos++] = (byte)(CRC & 0xff);//校验码低字节
            Buff[Pos++] = (byte)((CRC >> 8) & 0xff);//校验码高字节

            /*3.最后在这里把Buff的内容发送出去，长度为Pos */
            byte[] outBuff = new byte[Pos];
            Array.Copy(Buff, outBuff, Pos);
            Camera485Transmission(ref outBuff);
        }

        private static ushort MB_CRC16(ref byte[] Buff, int count)
        {
            byte CRCHi = 0xFF;
            byte CRCLo = 0xFF;
            int index;
            int i = 0;
            while ((count--) > 0)
            {
                index = CRCLo ^ Buff[i++];
                CRCLo = (byte)(CRCHi ^ _CRCHi[index]);
                CRCHi = _CRCLo[index];
            }
            return (ushort)(CRCHi << 8 | CRCLo);
        }

        private int cameraHand = -1;
        private int cameraType = 0;

        private void SerialPortCallback(int nSerialHandle, [MarshalAs(UnmanagedType.LPArray)] byte[] pRecvData, int uRecvSize, IntPtr pUserData)
        {
        }

        public void Camera485Transmission(ref byte[] Buff)
        {
            //相机透传的接口 发送协议数据
            if (cameraHand >= 0)
            {
                if (cameraType == 0)
                {
                    int CamSerialPortHand = VzClientSDK.VzLPRClient_SerialStart(cameraHand, 0, SerialPortCallback, (IntPtr)cameraHand); //打开串口
                    VzClientSDK.VzLPRClient_SerialSend(CamSerialPortHand, Buff, Buff.Length);//发送数据
                }
                else if (cameraType == 1)
                {
                    VzClientSDK.ICE_IPCSDK_TransSerialPort(cameraHand, Buff, Buff.Length);
                }
                else if (cameraType == 2)
                {
                    VzClientSDK.Net_TransRS485DataEx(cameraHand, 0, Buff, (ushort)Buff.Length);
                }
                System.Threading.Thread.Sleep(50);//不处理回复数据 需要延时一下
            }
            else
            {
                MessageBox.Show("没有连接相机", "ERROR");
            }
        }

        private int SerialPortCallback(int nSerialHandle, IntPtr pRecvData, int uRecvSize, IntPtr pUserData)
        {
            throw new NotImplementedException();
        }

        /*CRC 计算表1*/

        private static byte[] _CRCHi = {
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
            0x00, 0xC1, 0x81, 0x40
        };

        /*CRC 计算表2*/

        private static byte[] _CRCLo = {
            0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7,
            0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E,
            0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9,
            0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC,
            0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
            0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32,
            0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D,
            0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38,
            0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF,
            0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
            0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1,
            0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4,
            0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB,
            0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA,
            0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
            0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0,
            0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97,
            0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E,
            0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89,
            0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
            0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83,
            0x41, 0x81, 0x80, 0x40
        };

        private void DGOutList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }
    }
}